<?php

declare(strict_types=1);

namespace core;

/**
 * Base controller class
 */
abstract class Controller
{
    protected Request $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    protected function view(string $view, array $data = []): void
    {
        $viewPath = __DIR__ . "/../app/view/{$view}.php";
        if (!file_exists($viewPath) || !is_readable($viewPath)) {
            throw new \Exception("View not found: {$view}", 404);
        }

        // Extract data for view
        extract($data, EXTR_SKIP);

        // Load view
        require $viewPath;
    }

    protected function json(mixed $data, int $status = 200): void
    {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_THROW_ON_ERROR);
        exit;
    }

    protected function redirect(string $url, int $status = 302): never
    {
        header("Location: {$url}", true, $status);
        exit;
    }
}
